package com.javachmapi.springbootpoi.service.impl;

import com.javachmapi.springbootpoi.dao.UserDao;
import com.javachmapi.springbootpoi.entity.ExcelData;
import com.javachmapi.springbootpoi.entity.User;
import com.javachmapi.springbootpoi.service.ExcelService;
import com.javachmapi.springbootpoi.util.ExcelUtil;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private UserDao userDao;

    /**
     * 功能：导出
     * @param response
     * @param fileName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageSize, Integer pageNum) {
        log.info("导出数据开始。。。。。。");
        //查询数据并赋值给ExcelData
        List<User> userList = userDao.queryAllByLimit(pageSize, pageNum);
        List<String[]> list = new ArrayList<String[]>();
        for (User user : userList) {
            String[] arrs = new String[5];
            arrs[0] = String.valueOf(user.getId());
            arrs[1] = String.valueOf(user.getUsername());
            arrs[2] = String.valueOf(user.getPassword());
            arrs[3] = String.valueOf(user.getAddress());
            arrs[4] = String.valueOf(user.getState());
            list.add(arrs);
        }
        //表头赋值
        String[] head = {"序列", "用户名", "密码", "地址", "状态"};
        ExcelData data = new ExcelData();
        data.setHead(head);
        data.setData(list);
        data.setFileName(fileName);
        //实现导出
        try {
            ExcelUtil.exportExcel(response, data);
            log.info("导出数据结束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("导出数据失败。。。。。。");
            return false;
        }
    }

    /**
     * 功能：导入
     * @param fileName
     * @return
     */
    @Override
    public Boolean importExcel(InputStream inputStream, String fileName) {
        log.info("导入数据开始。。。。。。");
        try {
            List<Object[]> list = ExcelUtil.importExcel(inputStream,fileName);
            for (int i = 0; i < list.size(); i++) {
                User user = new User();
                user.setUsername((String) list.get(i)[1]);
                user.setPassword((String) list.get(i)[2]);
                user.setAddress((String) list.get(i)[3]);
                user.setState(Integer.parseInt(String.valueOf(list.get(i)[4])));
                userDao.insert(user);
            }
            log.info("导入数据结束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("导入数据失败。。。。。。");
            e.printStackTrace();
        }
        return false;
    }
}
